package priv.utrix.micro.controller;


import cn.hutool.core.util.StrUtil;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import priv.utrix.micro.annotation.Idempotent;
import priv.utrix.micro.entity.SysUser;
import priv.utrix.micro.entity.UserRole;
import priv.utrix.micro.handle.CustomerBlockHandler;
import priv.utrix.micro.json.ApiController;
import priv.utrix.micro.json.R;
import priv.utrix.micro.service.UserRoleService;
import priv.utrix.micro.service.SysUserService;

import java.io.Serializable;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 用户信息表(User)表控制层
 *
 * @author makejava
 * @since 2020-09-28 15:33:31
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/user")
public class SysUserController extends ApiController {

    final SysUserService userService;
    final UserRoleService userRoleService;

    /**
     * 测试幂等是否生效
     *
     * @return priv.utrix.micro.json.R<java.lang.Boolean>
     */
    @Idempotent(expireTime = 3, timeUnit = TimeUnit.MILLISECONDS)
    @PostMapping("/testIdempotent1")
    public R<Boolean> testIdempotent1() {
        log.info("Came in testIdempotent1 method");
        return success(true);
    }

    @Idempotent(expireTime = 133)
    @PostMapping("/testIdempotent2")
    public R<Boolean> testIdempotent2(@RequestParam String name) throws InterruptedException {
        TimeUnit.SECONDS.sleep(2);
        log.info("Idempotent's test arg is {}", name);
        return success(true);
    }

    @Idempotent(expireTime = 343)
    @GetMapping("/testIdempotent2")
    public R<Boolean> testIdempotent3(@RequestParam String name, @RequestParam Integer age) throws InterruptedException {
        TimeUnit.SECONDS.sleep(2);
        log.info("Idempotent's test arg is {}", name);
        return success(true);
    }

    /**
     * 根据当前登陆人的登录名获取当前登录用户信息
     *
     * @param username 用户登录名
     * @return priv.utrix.micro.json.R<java.util.Map<java.lang.String,java.lang.Object>>
     * @since 2020/10/23 9:01
     */
    @SentinelResource(value = "user/getLoginUser",
            fallbackClass = CustomerBlockHandler.class,
            defaultFallback = "handleDefaultQPSException")
    @GetMapping("/getLoginUser")
    public R<Map<String,Object>> getLoginUser(@RequestParam("username") String username) {
        // User user = userService.getByUsername(username);
        // log.info("获取登录用户的数据成功：{}", user.toString());
        // return success(BeanUtil.beanToMap(user));
        return success();
    }

    /**
     * 新增用户，数值先写死
     *
     * @param sysUser 新增用户封装类
     * @return priv.utrix.micro.json.R<java.lang.Boolean>
     * @since 2020/10/23 9:15
     */
    @Transactional(rollbackFor = Exception.class)
    @PostMapping("/add")
    public R<Boolean> add(@RequestBody SysUser sysUser) {
        if (StrUtil.isBlank(sysUser.getUsername()) || StrUtil.isBlank(sysUser.getPassword())) return failed("缺失必要的参数值");

        String encodePassword = PasswordEncoderFactories.createDelegatingPasswordEncoder().encode(sysUser.getPassword());
        sysUser.setPassword(encodePassword).setActualName("王五").setPhone("15312245026");
        this.userService.save(sysUser);

        UserRole userRole = new UserRole().setRoleId(2L).setUserId(3L);
        userRoleService.save(userRole);
        return success();
    }

    /**
     * 分页查询所有数据
     *
     * @param page 分页对象
     * @param sysUser 查询实体
     * @return 所有数据
     */
    @GetMapping
    public R selectAll(Page<SysUser> page, SysUser sysUser) {
        return success(this.userService.page(page, new QueryWrapper<>(sysUser)));
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("{id}")
    @PreAuthorize(value = "hasAnyRole('1')")
    public R<SysUser> selectOne(@PathVariable Serializable id) {
        return success(this.userService.getById(id));
    }

    /**
     * 新增数据
     *
     * @param sysUser 实体对象
     * @return 新增结果
     */
    @PostMapping
    public R<Boolean> insert(@RequestBody SysUser sysUser) {
        return success(this.userService.save(sysUser));
    }

    /**
     * 修改数据
     *
     * @param sysUser 实体对象
     * @return 修改结果
     */
    @PutMapping
    public R<Boolean> update(@RequestBody SysUser sysUser) {
        return success(this.userService.updateById(sysUser));
    }

    /**
     * 删除数据
     *
     * @param idList 主键结合
     * @return 删除结果
     */
    @DeleteMapping
    public R<Boolean> delete(@RequestParam("idList") List<Long> idList) {
        return success(this.userService.removeByIds(idList));
    }
}